<?php
class Wxinterface {
	//微信服务号
	private $_appid = "wx777fe378249a9de9";
	private $_appsecret = "bbdfeaa7b7f1b6eb667a089595089f02";
	private $_expires_in;
	private $_access_token;
	private $_wx_type = 'fuwu';
	//js-sdk
	//调用页面的完整URL
	private $_jsapi_url;
	//调用凭证
	private $_jsapi_ticket;
	private $_jsapi_ticket_expires_in;
	private $_jsapi_nonceStr;
	private $_jsapi_signature;
	private $_jsapi_timestamp;

	private $CI;
	
	//构造函数，获取Access Token
	//构造函数load传值只能有一个，类型为array
	public function __construct($config = array())
	{
		//初始化CI对象
		$this->CI = & get_instance();
		if(!empty($config)){
			$this->_appid = $config['appid'];
			$this->_appsecret = $config['appsecret'];
			//订阅号
			$this->_wx_type = $config['wxtype'];
		}
	
		//从缓存中获取access_token
		$this->CI->load->driver('cache',array('adapter' => 'apc', 'backup' => 'file'));		
		$cache_res = $this->CI->cache->get('wxinterface_access_token_'.$this->_wx_type);		
	    //超时重新获取
		if (empty($cache_res)){
			$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->_appid."&secret=".$this->_appsecret;
			$res = $this->http_request($url);
			$result = json_decode($res, true);
			
			if(!isset($result['errcode'])){
				$this->_access_token= $result["access_token"];
				$this->_expires_in = $result["expires_in"];
				$this->CI->cache->save('wxinterface_access_token_'.$this->_wx_type, $result, $result['expires_in']-600);
			}else{
				echo "errorcode: ".$result['errcode'].";errormsg: ".$result['errmsg'];exit;
			}			
		}else{
			$this->_expires_in = $cache_res["expires_in"];
			$this->_access_token = $cache_res["access_token"];
		}
	}
	
	public function get_jsapi_ticket()
	{
		//从缓存中获取jsapi_ticket
		$this->CI->load->driver('cache',array('adapter' => 'apc', 'backup' => 'file'));
		$cache_res = $this->CI->cache->get('wxinterface_jsapi_ticket_'.$this->_wx_type);
		//超时重新获取
		if (empty($cache_res)){
			$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$this->_access_token."&type=jsapi";
		    $res = $this->http_request($url);
		    $result = json_decode($res, true);
				
			if($result['errcode']==0){
				$this->_jsapi_ticket= $result["ticket"];
				$this->_jsapi_ticket_expires_in = $result["expires_in"];
				$this->CI->cache->save('wxinterface_jsapi_ticket_'.$this->_wx_type, $result, $result['expires_in']-600);
			}else{
				echo "errorcode: ".$result['errcode'].";errormsg: ".$result['errmsg'];exit;
			}
		}else{
			$this->_jsapi_ticket_expires_in = $cache_res["expires_in"];
			$this->_jsapi_ticket= $cache_res["ticket"];
		}		
	}
	
	public function getJsapiSignature($from_url = NULL)
	{
		$this->get_jsapi_timestamp();
        $this->get_jsapi_noncestr();
        $this->get_jsapi_ticket();
        
        if(!empty($from_url)){
        	$this->_jsapi_url=$from_url;
        }
        
        $Ori = "jsapi_ticket=".$this->_jsapi_ticket."&noncestr=".$this->_jsapi_nonceStr."&timestamp=".$this->_jsapi_timestamp."&url=".$this->_jsapi_url;
        $this->_jsapi_signature= sha1($Ori);
        return $this->_jsapi_signature;
	}
	
	public function get_jsapi_noncestr($length = 32)
	{
		$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
		$str = "";
		for ( $i = 0; $i < $length; $i++ )  {
			$str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
		}
		$this->_jsapi_nonceStr=$str;
	}
	
	public function get_jsapi_timestamp()
	{
		$this->_jsapi_timestamp = time();
	}
	
	public function getJsapiNonceStr()
	{
		return $this->_jsapi_nonceStr;
	}
	
	public function getAppid()
	{
		return $this->_appid;
	}
	
	public function getAppsecret()
	{
		return $this->_appsecret;
	}
	
	public function getJsapiTimestamp()
	{
		return $this->_jsapi_timestamp;
	}
	
	public function semantic_search($record)
	{
		$data = urldecode(json_encode($record));
		$url = "https://api.weixin.qq.com/semantic/semproxy/search?access_token=".$this->access_token;
		$res = $this->http_request($url, $data);
		return json_decode($res, true);
	}
	
	//HTTP请求（支持HTTP/HTTPS，支持GET/POST）
	protected function http_request($url, $data = null)
	{
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
		if (!empty($data)){
			curl_setopt($curl, CURLOPT_POST, 1);
			curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
		}
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
		$output = curl_exec($curl);
		curl_close($curl);
		return $output;
	}
	
	//日志记录
	private function logger($log_content)
	{
		if(isset($_SERVER['HTTP_APPNAME'])){   //SAE
			sae_set_display_errors(false);
			sae_debug($log_content);
			sae_set_display_errors(true);
		}else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
			$max_size = 500000;
			$log_filename = "log.xml";
			if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
			file_put_contents($log_filename, date('Y-m-d H:i:s').$log_content."\r\n", FILE_APPEND);
		}
	}
	
	//获取自定义菜单
	public function get_menu_info()
	{
		$url="https://api.weixin.qq.com/cgi-bin/menu/get?access_token=".$this->_access_token;
		$res=$this->http_request($url);
		return json_decode($res);
	}
	//设置自定义菜单
	public function set_menu($button)
	{
		$url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->_access_token;
		//echo $this->_access_token;exit;
		$res=$this->http_request($url,$button);
		return json_decode($res);
	}
	//检查客服是否在线
	public function check_online_kf()
	{
		$url="https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist?access_token=".$this->_access_token;
		//echo $this->_access_token;exit;
		$res=$this->http_request($url);
		return json_decode($res,true);
	}
	//查询已在微信注册ibeacon设备列表
	public function wx_device_search($data)
	{
		$url="https://api.weixin.qq.com/shakearound/device/search?access_token=".$this->_access_token;
		$res=$this->http_request($url,$data);
		return json_decode($res,true);
	}
	//查询微信注册ibeacon设备分组列表
	public function wx_device_group_list($data)
	{
		$url="https://api.weixin.qq.com/shakearound/device/group/getlist?access_token=".$this->_access_token;
		$res=$this->http_request($url,$data);
		return json_decode($res,true);
	}
	//查询微信注册ibeacon设备分组详情
	public function wx_device_group_detail($data)
	{
		$url="https://api.weixin.qq.com/shakearound/device/group/getdetail?access_token=".$this->_access_token;
		$res=$this->http_request($url,$data);
		return json_decode($res,true);
	}
	//新增微信注册ibeacon设备分组
	public function add_wx_device_group($data)
	{
		$url="https://api.weixin.qq.com/shakearound/device/group/add?access_token=".$this->_access_token;
		$res=$this->http_request($url,$data);
		return json_decode($res,true);
	}
	//修改微信注册ibeacon设备分组名
	public function edit_wx_device_group_name($data)
	{
		$url="https://api.weixin.qq.com/shakearound/device/group/update?access_token=".$this->_access_token;
		$res=$this->http_request($url,$data);
		return json_decode($res,true);
	}
	//删除修改微信注册ibeacon设备分组
	public function delete_wx_device_group($data)
	{
		$url="https://api.weixin.qq.com/shakearound/device/group/delete?access_token=".$this->_access_token;
		$res=$this->http_request($url,$data);
		return json_decode($res,true);
	}
	////从分组中移除设备
	public function delete_wx_device_from_group($data)
	{
		$url="https://api.weixin.qq.com/shakearound/device/group/deletedevice?access_token=".$this->_access_token;
		$res=$this->http_request($url,$data);
		return json_decode($res,true);
	}
	//新增微信注册ibeacon设备到分组
    public function add_wx_device_to_group($data)
    {
    	$url="https://api.weixin.qq.com/shakearound/device/group/adddevice?access_token=".$this->_access_token;
    	$res=$this->http_request($url,$data);
    	return json_decode($res,true);
    }
	
}